package com.liu.UCenterService.controller;


import com.liu.R;
import com.liu.UCenterService.entity.UcenterMember;
import com.liu.UCenterService.entity.vo.LoginVo;
import com.liu.UCenterService.entity.vo.RegisterVo;
import com.liu.UCenterService.service.UcenterMemberService;
import com.liu.serviceBase.exception.MyException;
import com.liu.utils.JwtUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author LSJ
 * @since 2022-02-02
 */
@RestController
@RequestMapping("/UCenterService/ucenter")
@CrossOrigin
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService ucenterMemberService;


    @PostMapping("userlogin")
    public R login(@RequestBody LoginVo loginVo){
        if (ObjectUtils.isEmpty(loginVo)){
            throw new MyException(20001,"登录用户的对象为空");
        }else {
            String token = ucenterMemberService.getLoginToken(loginVo);
            return R.ok().data("token",token);
        }
    }

    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo){
        if (ObjectUtils.isEmpty(registerVo)){
            throw new MyException(20001,"注册用户的对象为空");
        }else {
            boolean register = ucenterMemberService.register(registerVo);
            return register? R.ok().message("用户注册成功"):R.error().message("用户注册失败");
        }

        }

    @GetMapping("getUserInfoByToken")
    public R getUserInfoByToken(HttpServletRequest request) {
        // 根据Token得到用户的id、 进而得到用户的对象
        if (ObjectUtils.isEmpty(request)){
            throw new MyException(20001,"getUserInfoByToken();request为空");
        }
        try {
            String id = JwtUtils.getMemberIdByJwtToken(request);
            UcenterMember member = ucenterMemberService.getById(id);
            return R.ok().data("member", member);
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException(20001,"Token获取用户登录信息失败");
        }
    }

    @GetMapping("getUserInfoById/{uid}")
    public UcenterMember getUserInfoById(@PathVariable String uid){
        if (ObjectUtils.isEmpty(uid)){
            throw new MyException(20001,"uid为空");
        }
        System.out.println(uid);

        UcenterMember member = ucenterMemberService.getById(uid);
        return member;

    }

    // 查询某天注册人数
    @GetMapping("getRegisterMemberCount/{day}")
    public R getRegisterMemberCount(@PathVariable String day){
        if (ObjectUtils.isEmpty(day)){
            throw  new MyException(20001,"UcenterMemberController的 day为空");
        }
        int count =   ucenterMemberService.getRegisterMemberCount(day);
        return R.ok().data("RegisterMemberCount",count);

    }


}

